$(function(){
   $(document).ajaxStart(function(){
   }).ajaxStop(function() {
       $('#cluetip-inner').maskFields();
       $('#cluetip').draggable({handle:'h3'});
   });
   });

   (function($) {
 $.common = {
   dialog : null,

   emailReg : (function() {
       return new RegExp(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
   })(),

   checkEmail : function() {
       var email = $(this).val();
       if (email == null || email.length == 0) {
           return true;
       }
       else {
           return $.common.emailReg.test($(this).val());
       }
   },

   msgList : [],

   showMessage : function(options) {

       var settings = $.extend({
           msg     : 'Default Message',
           delay   : 1500,
           fadeOut : 'slow'
       }, options||{});

       $.common.msgList.push(settings.msg);

       $('.messageDiv').queue(function() {
           var msg = $.common.msgList.shift();
           var delay = settings.delay == undefined ? 1500 : settings.delay;
           $(".messageDiv").html("&nbsp;").show().html(msg);
           $(".messageDiv").delay(delay).fadeOut(settings.fadeOut);
           $(this).dequeue();
       });

   },

   //-------------------------------------------------------------------------
   // Mask phone number, numeric, alpha, alphanumeric field and email address.
   //
   // Usage: $('div.root').maskFields(); This statement will mask all child
   //        elements of 'div.root' that has class 'phoneno', 'numeric',
   //        'alpha', 'alphanumeric', and 'emailaddress'.
   //-------------------------------------------------------------------------
   maskFields: function(options) {
     var settings = $.extend({
       showIcon: false
     }, options || []);
     return this.each(function(){
         $(this).find('.phoneno').mask('(999)999-9999');

         $(this).find('.date-pick').datepicker({
             showOn: 'both',
             buttonImageOnly: true,
             changeMonth: true,
             changeYear: true
         }).mask('99/99/9999');

         $(this).find('.currency').maskMoney().attr('maxlength',10);
         $(this).find('.numeric').numeric();
         $(this).find('.alphanumeric').alphanumeric();
         $(this).find('.alpha').alpha();
         var year = new Date().getFullYear()
         $(this).find('.year').append("<option value='" + year + "'>" + year + "</option>").append("<option value='" + (++year) + "'>" + year + "</option>");

         $(this).find('.emailaddress').after('<span class="ui-icon ui-icon-close" style="display:none"/>');
         $(this).find('.emailaddress').bind('keyup', function() {
             var email = $(this).val();
             var ret = $.common.emailReg.test(email);
             if (email != "") {
                 if (ret) {
                     $(this).nextAll(".ui-icon-close").hide();
                 }
                 else {
                     $(this).nextAll(".ui-icon-close").show();
                 }
             }
             else {
                 $(this).nextAll(".ui-icon-close").hide();
             }
         });
     });
   },
   buildGfMenu : function(menuClass) {
       if ($('.tabContent').attr('role') == 'ROLE_ADMIN') {
           $('.' + menuClass + ' .menu').gfMenu({
               width:'6em'
           });

           $('.draggable').draggable({containment:'document'});

           $('.delete, .edit').show();
       }
   },
   isAdmin : function() {
       return ($('.tabContent').attr('role') == 'ROLE_ADMIN')
   },
   showDialog : function(msg, options) {
       var settings = $.extend({
           position: 'bottom',
           title   : 'Message'
       }, options||{});

       $.common.dialog = $('<div>').html(msg).dialog({position:settings.position, title:settings.title});
   },
   closeDialog : function() {
       $.common.dialog.dialog('close');
   }

 };

 $.fn.maskFields       = $.common.maskFields;
 $.fn.checkEmail       = $.common.checkEmail;
 $.showMessage         = $.common.showMessage;
 $.showDialog          = $.common.showDialog;
 $.closeDialog         = $.common.closeDialog;
 $.buildGfMenu         = $.common.buildGfMenu;
 $.isAdmin             = $.common.isAdmin;


   })(jQuery);

   var showMessage = function(msg) {
       $('<div>').html(msg).dialog({ position:'bottom', title:'Message', show:'fast' });
   }

   var closeCluetip = function() {
   $('#cluetip-close').triggerHandler('click');
   }

   var beforeSave = function() {
   $('.message').remove()
   }

   var processResponse = function(args) {
   if (typeof args != 'undefined' && typeof args.closeOnSuccess != 'undefined' && args.closeOnSuccess) {
       $('#cluetip-close').triggerHandler('click');
       return false;
   }
   if ($('.message').size() == 0) {
       // Close cluetip and show new list
       $('.content .tablesorter').replaceWith($('#cluetip-inner .tablesorter'));
       $('#cluetip-close').triggerHandler('click');
       setupAdminList(args);
   }
   else {
       // Show errors
       //showMessage($('.message').html());
       var height = $("#cluetip .bgiframe").height()
       $("#cluetip .bgiframe ~ div").height(height)
   }
   }

   var setupAdminList = function(args) {

   if (args && args.action != undefined) {
       window.controller = args.controller;
       window.action = args.action;
   }

   if ($('.content .tablesorter tbody > tr').size() > 0) {
       $('.content .tablesorter').each(function(){
           if ($(this).find('tbody > tr').size() > 0) {
               $(this).tablesorter( {
                   headers: {
                     0: {sorter: false}
                   },
                   widgets: ['zebra']
               });

               if (args && args.cluetipWidth) {
                   if (args.cluetipHeight != undefined) {
                       $(".edit > a, .show > a, .add > a").cluetip({activation:'click', sticky:true, closePosition:'title', width:args.cluetipWidth, height:args.cluetipHeight, ajaxCache: false});
                   }
                   else {
                       $(".edit > a, .show > a, .add > a").cluetip({activation:'click', sticky:true, closePosition:'title', width:args.cluetipWidth, ajaxCache: false});
                   }
               }
               else {
                   $(".edit > a, .show > a, .add > a").cluetip({activation:'click', sticky:true, closePosition:'title', ajaxCache: false});
               }

               $('.delete, .edit').show();

               $(this).tablesorterPager({container: $("#pager"), positionFixed: false});
           }
       });
   }
   else {
       if ($('#menu-content .tablesorter tbody > tr').size() > 0) {
           $('#menu-content .tablesorter').tablesorter( {
               headers: {
                 0: {sorter: false}
               },
               widgets: ['zebra']
           }).tablesorterPager({container: $("#pager"), positionFixed: false});

           return;
       }
   }

   if (args && args.cluetipWidth) {
       if (args.cluetipHeight != undefined) {
           $(".create").cluetip({activation:'click', sticky:true, closePosition:'title', width:args.cluetipWidth, height:args.cluetipHeight, ajaxCache: false});
       }
       else {
           $(".create").cluetip({activation:'click', sticky:true, closePosition:'title', width:args.cluetipWidth, ajaxCache: false});
       }
   }
   else {
       $(".create").cluetip({activation:'click', sticky:true, closePosition:'title', ajaxCache: false});
   }
   }

   var post = function(args) {

   $.ajax({
         url: args.url,
         beforeSend:function() {
             if (args.beforeSend != undefined) {
                 args.beforeSend();
             }
         },
         global: false,
         type: "POST",
         data: args.data,
         error: function() {
             if (args.error != undefined) {
                 args.error();
             }
         },
         success: function(response){
             if (args.success != undefined) {
                 args.success(response);
             }
         }
      }
   );

   }

   var changeList = function(checkbox, url) {

   var args = {
       url: url,
       data: {
           showAll : $('.showAll:checked').size() == 1 ? 'Y' : 'N'
       },
       success: function(response){
           $('.content').html(response);
       }
   }

   post(args);
   }

   var changeActiveSemester = function(semesterId) {
   var args = {
       url: '/XiLin/globalVariable/setActiveSemester',
       data: {
           semesterId : semesterId,
           redirectAction : window.action,
           redirectController : window.controller
       },
       success: function(response){
           if ($('.content').size() > 0) {
               $('.content').html(response);
           }
           else {
               $('#menu-content').html(response);
           }
       }
   }

   post(args);
   }

   var changeStudent = function(studentId) {
   var args = {
       url: '/XiLin/classRegister/selectStudent',
       data: {
           studentId : studentId,
           redirectAction : window.action,
           redirectController : window.controller
       },
       success: function(response){
           if ($('.content').size() > 0) {
               $('.content').html(response);
           }
           else {
               $('#menu-content').html(response);
           }
       }
   }

   post(args);
   }

   var bookOption = function(classId, bookChecked, studentId) {
   var args = {
       url: '/XiLin/classRegister/bookOption',
       data: {
           classId : classId,
           bookChecked : bookChecked,
           studentId: studentId,
           redirectAction : window.action,
           redirectController : window.controller
       },
       success: function(response){
           if ($('.content').size() > 0) {
               $('.content').html(response);
           }
           else {
               $('#menu-content').html(response);
           }
       }
   }

   post(args);
   }


   var alertDialog = null

   function showAlertDialog() {
   if (alertDialog == null) {
       alertDialog = $("<div><p><span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 50px 0;'></span>" +
         "Are you sure you want to delete?</p></div>").dialog({
               title: 'Delete',
               modal: true,
               dialogClass: 'alert',
               open: function(event, ui) {
                   $('.ui-dialog a').remove();
                   $(this).dialog('option', 'position', ['center','middle']);
               },
               buttons: {
                   No: function() {
                       $(this).dialog('close');
                       return false;
                   },
                   Yes: function() {
                       $(this).dialog('close');
                       return true;
                   }
               }
           });
   }
   else {
       alertDialog.dialog('open');
   }
   }

   var msgDialog = null

function showTextMessage(container) {
   var msg = container.html();

   if (msgDialog) {
       msgDialog.find('.textMessage').html(msg);
   }
   else {
       msgDialog = $('<DIV style="PADDING-BOTTOM: 0px; MARGIN-TOP: 20px; PADDING-LEFT: 0.7em; PADDING-RIGHT: 0.7em; PADDING-TOP: 0px">class="ui-state-highlight ui-corner-all"');
       msgDialog.append('<P><SPAN style="FLOAT: left; MARGIN-RIGHT: 0.3em" class="ui-icon ui-icon-info"></SPAN><STRONG>Message!</STRONG><span class="textMessage"></span></P>');
       msgDialog.find('.textMessage').html(msg);
   }
   container.html(msgDialog);
}

function findBy(property, value, domainClass, domainName) {
    //alert(">>> domainClass=" + domainClass);
    //if (value.length == 0) {
    //    alert('Enter search data');
    //    return false;
    //}

    var properties = property.split(',')
    var url = window.location.href + 'search/search';
    var args = {
        url: url,
        data: {
            value       : value,
            property    : properties[0],
            type        : properties[1],
            domainClass : domainClass,
            domainName  : domainName
        },
        success: function(response){
            if ("0" == response) {
                alert("No data found");
            }
            else {
                $('.searchResult').html(response);
            }
        }
    }

    post(args);
}